import { Modal, QRCode, Popover, QRCodeProps, message  } from "antd"
import type {  } from "antd"
import { useEffect, useMemo, useState, useRef, useCallback } from "react"
import IHttp from "@/services/http.service";
import { Subscription } from 'rxjs';

type IProps = {
  item: API.AccountItem | undefined
  onRefreshTable: () => void
}

export default function AccountBindPopover({ item, onRefreshTable }: IProps) {
  const [, setRandom] = useState<number>(0)
  const prepareSubscription = useRef<Subscription>()
  const checkSubscription = useRef<Subscription>()
  const checkStateTimer = useRef<NodeJS.Timeout>()
  const [open, setOpen] = useState(false);
  const sessionData = useRef<API.BindAccountSession>()
  // const [sessionData, setSessionData] = useState<API.BindAccountSession | undefined>(undefined)
  useEffect(() => {
    if (open) {
      prepareBindSession()
    }
    return () => {
      prepareSubscription.current?.unsubscribe()
      checkSubscription.current?.unsubscribe()
      checkStateTimer.current && clearInterval(checkStateTimer.current)
      sessionData.current = undefined
    }
  }, [open])
  function prepareBindSession() {
    if (!item?.id) return
    prepareSubscription.current = IHttp.bindAccountPrepare(item?.id).subscribe(
      res => {
        if (!res.status) {
          sessionData.current = {hash: "", targetUri: "", state: 2}
          setRandom(Math.random())
          return
        }
        sessionData.current = res.data
        setRandom(Math.random())
        startCheckTimer()
      }
    )
  }

  function startCheckTimer() {
    checkStateTimer.current = setInterval(() => {
      if (!item?.id || !sessionData.current?.hash) return
      checkSubscription.current = IHttp.bindAccountCheck(item?.id, {hash: sessionData.current?.hash}).subscribe(
        res => {
          // 过期了！！！
          if (!res.status && res.code === -2000) {
            sessionData.current = {hash: "", targetUri: "", state: 2}
            setRandom(Math.random())
            clearInterval(checkStateTimer.current)
            return
          }
          if (!res.status) return
          if (res.data.state === 3) {
            clearInterval(checkStateTimer.current)
            message.success("绑定成功!")
            setOpen(false)
            onRefreshTable()
            return
          }
          sessionData.current = {...sessionData.current, state: res.data.state} as API.BindAccountSession
          setRandom(Math.random())
        }
      )
    }, 1500)
  }
  function handleOpenChange(newOpen: boolean) {
    setOpen(newOpen)
  }
  const qrCodeStatus: QRCodeProps["status"] = useMemo(() => {
    if (!sessionData.current) return "loading"
    if (sessionData.current.state === 2) return "expired"
    if (sessionData.current.state === 1) return "scanned"
    return "active"
  }, [sessionData.current])
  const content = (
    <div className="">
      <QRCode status={qrCodeStatus} size={200} value={sessionData.current?.targetUri || "https://baidu.com"}></QRCode>
    </div>
  )
  return (
    <Popover 
      title={`正在绑定 ${item?.name}`}
      content={content}
      open={open}
      onOpenChange={handleOpenChange}
      destroyTooltipOnHide
      trigger={["click"]}
    >
      <a className="">绑定</a>
    </Popover>
  )
}